package com.lz.ub.core

import com.lz.ub.COMMAND_CONNECTED_DELAYED
import com.lz.ub.UBCDevice
import com.lz.ub.UBCOperator
import com.lz.ub.UBCWritable
import java.util.*

/**
 * @author You
 * UBC蓝牙连接器, 连接流程
 */
internal class UBCConnection(private val operator: UBCOperator) : UBCWritable {

    //待连接的设备
    private val pendingDevices = LinkedList<UBCDevice>()

    //当前正在连接的设备
    private var currentDevice: UBCDevice? = null

    //推入要连接的设备, 推入前要判断状态[isAvailable]
    fun pushPendingDevices(devices: List<UBCDevice>) {
        pendingDevices.addAll(devices)
        next(false)
    }

    private fun next(delayed: Boolean) {
        currentDevice = pendingDevices.pollFirst()
        if (currentDevice != null) {
            val device = currentDevice!!
            if (device.needConnected()) {
                if (delayed) Thread.sleep(COMMAND_CONNECTED_DELAYED)
                operator.write(device.connectCmd, this)
            } else {
                next(delayed)
            }
        } else {
            operator.connectOver()
        }
    }

    override val label: String = "Connection"

    override fun responseOk() {
        currentDevice?.connecting()
        next(true)
    }

    override fun responseFail() {
        next(true)
    }

    override fun close() {
        pendingDevices.clear()
        currentDevice = null
    }

    override fun isAvailable(): Boolean = pendingDevices.isEmpty() && currentDevice == null
}